/**
 * 
 */
package com.usc.entme;

import android.app.Activity;
import android.app.LauncherActivity.ListItem;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//Karan  Added*********************************************
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.ArrayAdapter;
//Karan Added**************************************
/**
 * 
 * This is the main class that displays the Movies main screen.
 * @author pranav
 *
 */
public class Movies extends ListActivity /*implements OnItemSelectedListener*/ {
	//Karan Added**************************************
	private String TAG="Kathan";
	private static Context context;
	private static final int REQUEST_CODE = 1234;
	ArrayList<MoviesObject> MoviesObjects = new ArrayList<MoviesObject>();
	boolean imdbMovies=true;
	boolean boxOffice=false;
	boolean settingsOpened=false;
	
	URL jsonURL;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		context = this;
		
		//Karan  Added*********************************************
		//setContentView(R.layout.movies);
		//setListAdapter(new ArrayAdapter<String>(this, R.layout.movieitem, COUNTRIES));
		getPref();
		populateMovies();
		
		
		/*ListView moviesListView = getListView();
		 
		//setListAdapter(new ArrayAdapter(this,R.layout.movieitem, this.fetchJson()));
		//moviesListView.setOnItemSelectedListener(this);
		moviesListView.setTextFilterEnabled(true);
		moviesListView.setOnItemClickListener(new OnItemClickListener() 
		{
			    public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
			    {
			    	
			    	MoviesObject mo = new MoviesObject();
					mo = MoviesObjects.get(position);
					
					String movieTitle = mo.title;
					//Log.v(TAG, movieTitle);
					String movieUrl = mo.Url;
					//Log.v(TAG, movieUrl);
								   
					
					Intent i = new Intent(Movies.this,MoviesDesc.class);
					i.putExtra("movieTitle", movieTitle);
					i.putExtra("movieUrl", movieUrl);
					startActivity(i);
				}
			  });
*/
		 //setContentView(textview);		
	}


	/* (non-Javadoc)
	 * @see android.app.ListActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getPref();
		if(settingsOpened)
		{
			populateMovies();
		}
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}


	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}


	/**
	 * 
	 */
	public void populateMovies() {
		MoviesObjects.clear();
		if(imdbMovies)
		{
			Log.d(TAG,"Fetching JSON for IMDB...");
			fetchJsonImdb();
			Log.d(TAG,"JSON Fetched for IMDB");
		}
		if(boxOffice)
		{
			Log.d(TAG,"Fetching JSON for BOM...");
			try {
				fetchJsonBom();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d(TAG,"JSON Fetched for BOM");
		}
		
		
		List<MoviesObject> movieList = new ArrayList<MoviesObject>(MoviesObjects.size());
		
		Log.d(TAG,"Adding objects in movieList");
		for(MoviesObject mo : MoviesObjects)
		{
			movieList.add(mo);
		}
		
		Log.d(TAG,"Calling method ListItemArrayMovies...");
		setListAdapter(new ListItemArrayAdapterMovies(this,R.layout.movieitem,movieList));
		Log.d(TAG,"Called ListItemArrayAdapterMovies");
		settingsOpened=false;
	}
	
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		String url = MoviesObjects.get(position).getUrl();
		//Log.e(TAG, "the msg " + msg);
		
			Intent i = new Intent(Movies.this,Url.class );
			Bundle b = new Bundle();
	        b.putString("passed", url);
	        i.putExtras(b);
	        startActivity(i);
		
		
	}
	public void getPref() {
		SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(getBaseContext());
		 
		 boxOffice = prefs.getBoolean("boxOfficePref", false);
		 
		 imdbMovies = prefs.getBoolean("imdbMoviesPref", true);
	}
	
	//Karan  Added*********************************************	
	public void fetchJsonImdb()
	{
		//ArrayList<String> listItems= new ArrayList<String>();
		try
		{
			jsonURL= new URL("http://m.imdb.com/chart/moviemeter_json");
			URLConnection conJSON=jsonURL.openConnection();
			BufferedReader inBufRead=new BufferedReader(new InputStreamReader(conJSON.getInputStream()));
			String line;
			
			line= inBufRead.readLine();
			String [] st;
			st = line.split("list\":");
			
			if(st[1] != null)
			{
				//Log.d(TAG,""+st[1].charAt(st[1].length()-1));
				JSONArray ja = new JSONArray(st[1].substring(0, st[1].length()-1));
				for (int i = 0; i < ja.length(); i++) 
				{
					//Log.d(TAG,ja.get(i).toString());
					JSONObject jo = (JSONObject) ja.get(i);
					
					
					
					JSONObject imgdetails = jo.getJSONObject("img");
					String imageUrl = imgdetails.getString("url");
					//Log.d(TAG,imageUrl);
					//Log.d(TAG,imgdetails);
					
					MoviesObject mo = new MoviesObject(jo.getString("title"), "http://m.imdb.com" + jo.getString("url"), jo.getString("detail"), imageUrl);
					//removed to match the constructor
					//mo.setter(jo.getString("title"), "m.imdb.com" + jo.getString("url"), jo.getString("detail"), imageUrl);
					MoviesObjects.add(mo);
					
					
					//listItems.add(jo.getString("title"));
	            }		
			}
		}
		catch (MalformedURLException e) 
		{
			e.printStackTrace();
        } 
		catch (IOException e) 
		{
			e.printStackTrace();
        }
		catch (JSONException e) 
		{
			e.printStackTrace();
        }
		//return listItems;
	}

	//Kathan
	public void fetchJsonBom() throws JSONException
	{
		InputStream is = this.getResources().openRawResource(R.raw.jsonstringbom);
	    BufferedReader br = new BufferedReader(new InputStreamReader(is));
	    String readLine = null;

	    
	    int count=0;
	    JSONArray ja = null;
	    
	    try 
	    {
	        // While the BufferedReader readLine is not null 
	        while ((readLine = br.readLine()) != null) 
	        {
	        	ja = new JSONArray(readLine);
	        	count++;
	        	Log.d(TAG, readLine);
	        }

	        for (int i = 0; i < ja.length(); i++) 
			{
				JSONObject jo = (JSONObject) ja.get(i);
			
				String title = jo.getString("title");
				String movieDescUrl = "http://www.boxofficemagazine.com/reviews/2011-11-"+title.toLowerCase().replace(" ", "-");
				//MoviesObject mo = new MoviesObject(title, movieDescUrl, jo.getString("desc"), jo.getString("image"));
				MoviesObject mo = new MoviesObject(jo.getString("title"), jo.getString("embedURL"), jo.getString("desc"), jo.getString("image"));
				Log.d(TAG,movieDescUrl);
				MoviesObjects.add(mo);
				
            }	
	        Log.d(TAG,Integer.toString(count));
	        
	        // Close the InputStream and BufferedReader
	        is.close();
	        br.close();

	    }
	    catch (IOException e) 
	    {
	        e.printStackTrace();
	    }
	}
	
	//Karan  Added*********************************************
	/*@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) 
	{
		MoviesObject mo = new MoviesObject();
		mo = MoviesObjects.get(position);
		
		String abc = mo.title;
		String cde = mo.Url;
		
	}
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}*/
	
	private void startVoiceRecognitionActivity()
	{
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
		startActivityForResult(intent, REQUEST_CODE);
	}

	/**
	 * Handle the results from the voice recognition activity.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
		{
			// Populate the wordsList with the String values the recognition engine thought it heard
			ArrayList<String> matches = data.getStringArrayListExtra(
					RecognizerIntent.EXTRA_RESULTS);
			//      wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
			//            matches));

			if(matches.isEmpty())
			{
				Toast.makeText(context, "No Match found", 2);
			}
			else
			{
				Boolean flag = false;
				for(int i=0;i<matches.size();i++)
				{
					if(matches.get(i).equalsIgnoreCase("news"))
					{
							Log.d(TAG, "News detected int Vocie Recognition");
							Intent intent = new Intent(context,News3DActivity.class);
							startActivity(intent);
							flag =true;
							break;
					}
					if(matches.get(i).equalsIgnoreCase("movies"))
					{
						Intent intent = new Intent(context,Movie3DActivity.class);
						startActivity(intent);
						flag =true;
						break;
					}
					if(matches.get(i).equalsIgnoreCase("sports"))
					{
						Intent intent = new Intent(context,Sports3DActivity.class);
						startActivity(intent);
						flag =true;
						break;
					}
					

				}
				if(!flag)
				{
					
					Toast.makeText(context, "No Match found. Try Again!!", Toast.LENGTH_LONG);
					Log.d(TAG, "No match found");
				}

			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intentActivity;
		// Handle item selection
		switch (item.getItemId()) {
		
		case R.id.threeD:
			if(getLocalClassName().contains("3D")){
				if(getLocalClassName().contains("News")){
				intentActivity = new Intent(getBaseContext(),EntmeActivity.class);	
				intentActivity.putExtra("tabHostIndex", 0);
			    startActivity(intentActivity);
				} else if(getLocalClassName().contains("Movies")){
					intentActivity = new Intent(getBaseContext(),EntmeActivity.class);
					intentActivity.putExtra("tabHostIndex", 1);
					startActivity(intentActivity);
				} else if(getLocalClassName().contains("Sports")){
					intentActivity = new Intent(getBaseContext(),EntmeActivity.class);
					intentActivity.putExtra("tabHostIndex", 2);
					startActivity(intentActivity);
				}			    
			}else{
				
				if(getLocalClassName().equalsIgnoreCase("News")){
					intentActivity = new Intent(getBaseContext(),News3DActivity.class);			
				    startActivity(intentActivity);
					} else if(getLocalClassName().equalsIgnoreCase("Movies")){
						intentActivity = new Intent(getBaseContext(),Movie3DActivity.class);			
						startActivity(intentActivity);
					} else if(getLocalClassName().equalsIgnoreCase("Sports")){
						intentActivity = new Intent(getBaseContext(),Sports3DActivity.class);			
						startActivity(intentActivity);
					}	
			}
			
			return true;			
		case R.id.Settings:
			settingsOpened=true;
			intentActivity = new Intent(getBaseContext(),Preferences.class);
			startActivity(intentActivity);
			return true;
		case R.id.home:
			intentActivity = new Intent(getBaseContext(),EntmeGridViewActivity.class);
			startActivity(intentActivity);
			return true;
		case R.id.speak:
			startVoiceRecognitionActivity();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}
}

class MoviesObject
{
	public String title;
	public String Url;
	public String detail;
	public String imageUrl;
	
	public MoviesObject(String title, String Url, String detail, String imageUrl) {
		this.title = title;
		this.Url = Url;
		this.detail = detail;
		this.imageUrl = imageUrl;
	}

	/*
	 *PV : instead of using a seperate method I have created a constructor to serve this purpose 
	 *
	public void setter(String title, String Url, String detail, String imageUrl)
	{
		this.title = title;
		this.Url = Url;
		this.detail = detail;
		this.imageUrl = imageUrl;
	}*/
	
	/**
	 * @return the url
	 */
	public String getUrl() {
		return Url;
	}

	/**
	 * @param url the url to set
	 */
	public void setUrl(String url) {
		Url = url;
	}

}